"""
日志业务逻辑模块
处理日志流相关的业务逻辑
"""

import time
import random
import json

# 模拟日志生成器的状态
log_generator_running = False
log_generator_thread = None

def get_log_generator_status():
    """获取日志生成器状态"""
    return log_generator_running

def set_log_generator_status(status):
    """设置日志生成器状态"""
    global log_generator_running
    log_generator_running = status

def get_log_generator_thread():
    """获取日志生成器线程"""
    global log_generator_thread
    return log_generator_thread

def set_log_generator_thread(thread):
    """设置日志生成器线程"""
    global log_generator_thread
    log_generator_thread = thread

def log_generator():
    """
    日志生成器函数，在后台线程中运行
    模拟持续生成日志数据
    """
    global log_generator_running
    log_levels = ['INFO', 'DEBUG', 'WARN', 'ERROR']

    # 持续生成日志直到停止
    while log_generator_running:
        # 随机生成日志条目
        log_entry = {
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "level": random.choice(log_levels),
            "message": f"这是第{random.randint(1, 1000)}条测试日志消息",
            "source": random.choice(["server", "database", "api", "worker"])
        }

        # 将日志条目转换为JSON格式
        yield f"data: {json.dumps(log_entry)}\n\n"

        # 模拟日志生成间隔
        time.sleep(random.uniform(0.5, 2))
